/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 047.c
 * high definition multiplication
 ***********************************************************************************************/

#include <stdio.h>
#include <string.h>

/*
 *
 */

#define LENGTH 100

int printNumber(int* number)
{
	int i = number[0];
	for (; i > 0; i--)
		printf("%d", number[i]);
	printf("\n");
}

int multiple(int* a, int* b, int*c)
{
	int i = 0;
	int add = 0;
	for (i = 1; i <= b[0]; i++)
	{
		add = 0;
		int j = 0;
		for (j = 1; j <= a[0]; j++)
		{
			int mul = b[i]*a[j];
			if (c[i+j-1] == -1)
				c[i+j-1] = 0;
			int temp = c[i+j-1] + mul + add;
			c[i+j-1] = temp%10;
			add = temp/10;
		}
	}
	if (add != 0)
		c[0] = a[0] + b[0];
	else
		c[0] = a[0] + b[0] - 1;
}

int main()
{
	// array[0] is count of digits in high definition number
	int a[LENGTH+1];
	int b[LENGTH+1];
	int c[LENGTH+LENGTH+1];

	memset(a, -1, sizeof(int)*(LENGTH+1));
	memset(b, -1, sizeof(int)*(LENGTH+1));
	memset(c, -1, sizeof(int)*(LENGTH+LENGTH+1));

	// 2 is for '*' and '\0'
	char str[LENGTH+LENGTH+2];
	memset(str, 0, (LENGTH+LENGTH+2));

	printf("Plz input multiple equation (A*B): ");
	scanf("%s", str);

	int i = strlen(str), j = 1;
	i -= 1;
	while (str[i] != '*')
	{
		b[j++] = str[i--] - '0';
	}
	b[0] = j-1;
	i -= 1;
	j = 1;
	while (i >= 0)
	{
		a[j++] = str[i--] - '0';
	}
	a[0] = j-1;

	printNumber(a);
	printf("*\n");
	printNumber(b);

	multiple(a, b, c);

	printf("=\n");
	printNumber(c);
}

